package thread.demo05_2.ReentrantReadWriteLock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 写写互斥
 * 
 * @author mengzhang6
 *
 */
public class ReentrantReadWriteLockDemo2 {
	private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

	public static void main(String[] args) {

		ReentrantReadWriteLockDemo2 demo = new ReentrantReadWriteLockDemo2();

		new Thread(() -> demo.write(), "ThreadA").start();
		new Thread(() -> demo.write(), "ThreadB").start();
		/**
		 * 可以看出执行结果大致差了5秒的时间，可以说明多个写线程是互斥的。
		 */
	}

	private void write() {
		try {
			try {
				lock.writeLock().lock();
				System.out.println("获得写锁" + Thread.currentThread().getName() + " 时间:" + System.currentTimeMillis());
				// 模拟写操作时间为5秒
				Thread.sleep(5000);
			} finally {
				lock.writeLock().unlock();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
